class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> res;
        if(matrix.size()==0)
            return res;
        int m=matrix.size();//行
        int n=matrix[0].size();//列
        //从外到内有几圈
        int times=(min(m,n)%2==0)?min(m, n)/2:min(m,n)/2+1;
        int c1,c2,r1,r2;  //画边界
        c1=0;c2=n-1;
        r1=0;r2=m-1;
        for(int i=0;i<times;i++)
        {
            int c,r;
            for(c=c1;c<=c2;c++) res.push_back(matrix[r1][c]);
            for(r=r1+1;r<=r2;r++) res.push_back(matrix[r][c2]);
            if(r1<r2&&c1<c2){
            for(c=c2-1;c>c1;c--) res.push_back(matrix[r2][c]);
            for(r=r2;r>r1;r--) res.push_back(matrix[r][c1]);
            }
            r1++;
            r2--;
            c1++;
            c2--;
        }
        return res;
    }
};